<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;

class Authenticate
{
    /**
     * The authentication guard factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param \Illuminate\Contracts\Auth\Factory $auth
     * @return void
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param string|null $guard
     * @return mixed
     */
    public function handle2($request, Closure $next, $guard = null)
    {
        if ($this->auth->guard($guard)->guest()) {
            return response('Unauthorized.', 401);
        }

        return $next($request);
    }

    public function handle($request, Closure $next, $guard = null)
    {
        try {
            $sKey = $request->header('X-WX-Skey');

            if (!$sKey) {
                $sKey = $request->header('X-WX-SKEY');
            }
            if (env('API_AUTH') && !$sKey) {
                return [
                    'code' => -1,
                    'message' => '非法请求，请在微信小程序中使用',
                ];
            }

            $session = $this->auth->guard($guard)->user();

            if (!$session && env('API_AUTH')) {
                return [
                    'code' => -1,
                    'message' => '没有获取到用户信息，请强制关闭微信后重新授权',
                ];
            }

            return $next($request);
        } catch (\Exception $exception) {
            echo $exception->getMessage();
        }
    }
}
